package com.rongzhe.house.ui.view;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.rongzhe.house.R;
import com.rongzhe.house.ui.activity.H5BaseActivity;
import com.rongzhe.house.utils.UIUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by huang on 2017/11/17.
 */

public class BannerView extends RelativeLayout {

    private ViewPager mImageViewPager;
    private RadioGroup mCurrentPageGroup;
    private Drawable mRadioButtonDrawable;
    private LayoutInflater mInflater;
    private static final int ID_BASE = 0x000100;
    private boolean mLoop;
    private List<BannerData> mDatas;

    public BannerView(Context context) {
        this(context, null);
    }

    public BannerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public BannerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        TypedArray tArray = context.obtainStyledAttributes(attrs,
                R.styleable.BannerView);
        mLoop = tArray.getBoolean(R.styleable.BannerView_loop, false);
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mImageViewPager = new ViewPager(context);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        addView(mImageViewPager, layoutParams);
        mCurrentPageGroup = new RadioGroup(context);
        mCurrentPageGroup.setOrientation(LinearLayout.HORIZONTAL);
        LayoutParams layoutParams2 = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        layoutParams2.alignWithParent = true;
        layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams2.addRule(RelativeLayout.CENTER_HORIZONTAL);
        layoutParams2.setMargins(0,0,0, UIUtils.dip2px(context, 20));
        addView(mCurrentPageGroup, layoutParams2);
        mRadioButtonDrawable = tArray.getDrawable(R.styleable.BannerView_raido_button);
        tArray.recycle();
    }

    public void setDatas(List<BannerData> datas) {
        this.mDatas = datas;
        init();
        invalidate();
    }

    public void init() {
        mImageViewPager.setAdapter(new ImageViewPagerAdapter());
        mImageViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                if (needRaidoButton()) {
                    RadioButton child = (RadioButton) mCurrentPageGroup
                            .getChildAt(position % getItemCount());
                    if (!child.isChecked()) {
                        child.setChecked(true);
                    }
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        initRadioButton();
    }

    private boolean needRaidoButton() {
        return getItemCount() > 1;
    }

    private void initRadioButton() {
        if (!needRaidoButton()) {
            return;
        }
        mCurrentPageGroup.removeAllViews();
        for (int i = 0; i < getItemCount(); i++) {
            RadioButton radioButton = (RadioButton) mInflater.inflate(R.layout.raido_button,
                    mCurrentPageGroup, false);
            LinearLayout.LayoutParams layoutParams =
                    (LinearLayout.LayoutParams) radioButton.getLayoutParams();
            layoutParams.setMargins(UIUtils.dip2px(getContext(), 10), 0,0, 0);
            radioButton.setEnabled(false);
            if (i == 0) {
                layoutParams.setMargins(0, 0, 0, 0);
            }
            radioButton.setId(ID_BASE + i);
            mCurrentPageGroup.addView(radioButton, layoutParams);
        }
        if (mCurrentPageGroup.getChildCount() > 0)
            ((RadioButton) mCurrentPageGroup.getChildAt(0)).setChecked(true);
    }

    private int getItemCount() {
        return mDatas == null ? 0 : mDatas.size();
    }

    private class ImageViewPagerAdapter extends PagerAdapter {
        private List<ImageView> mImageViews = new ArrayList<>();
        public ImageViewPagerAdapter() {
            for(int i = 0; i < getItemCount(); i++) {
                ImageView imageView = new ImageView(getContext());
                imageView.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                final BannerData itemData = mDatas.get(i);
                if (TextUtils.isEmpty(itemData.getImageUrl())) {
                    imageView.setImageResource(itemData.getImageId());
                } else {
                    Picasso.with(getContext()).load(itemData.getImageUrl()).into(imageView);
                }
                if (!TextUtils.isEmpty(itemData.getClickUrl())) {
                    imageView.setClickable(true);
                    imageView.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = H5BaseActivity.getH5BaseActivityIntent(getContext(),
                                    null, itemData.getClickUrl());
                            getContext().startActivity(intent);
                        }
                    });
                }
                mImageViews.add(imageView);
            }
        }

        @Override
        public int getCount() {
            return mLoop ? Integer.MAX_VALUE : getItemCount();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            int newPosition = position % getItemCount();
            ImageView iv = mImageViews.get(newPosition);
            // 先移除再添加，更新图片在container中的位置（把iv放至container末尾）
            container.removeView(iv);
            container.addView(iv);
            return iv;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
        }
    }

    public static class BannerData {
        int imageId;
        String imageUrl;
        String clickUrl;

        public BannerData(int imageId, String imageUrl, String clickUrl) {
            this.imageId = imageId;
            this.imageUrl = imageUrl;
            this.clickUrl = clickUrl;
        }

        public int getImageId() {
            return imageId;
        }

        public String getImageUrl() {
            return imageUrl;
        }

        public String getClickUrl() {
            return clickUrl;
        }
    }
}
